package com.zhuss.core.processor;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.zhuss.appconfig.SystemCache;
import com.zhuss.bean.bo.core.login.TokenBo;
import com.zhuss.bean.bo.core.login.app.BindBo;
import com.zhuss.bean.bo.core.user.CreateUserBo;
import com.zhuss.bean.unit.core.user.UserBean;
import com.zhuss.bean.vo.core.login.app.BindVo;
import com.zhuss.bean.vo.core.user.DetailUserVo;
import com.zhuss.common.AbstractProcessor;
import com.zhuss.common.Processor;
import com.zhuss.core.db.dao.ext.UserDao;
import com.zhuss.core.db.entity.User;
import com.zhuss.db.entity.OpLog;
import com.zhuss.enums.IsEnum;
import com.zhuss.enums.LogActionEnum;
import com.zhuss.enums.MoudleEnum;
import com.zhuss.enums.Sex;
import com.zhuss.enums.SystemCHEnum;
import com.zhuss.enums.SystemEnum;
import com.zhuss.exception.DzcxException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.JsonUtil;

/**
 * app
 * 登录 processor
 * @Author: zhushanshuo
 * @Date: 2020/12/29 17:55
 */
@Component("bindProcessor")
public class BindProcessor extends AbstractProcessor<BindVo, BindBo> implements Processor<BindVo, BindBo> {

	@Autowired
	@Qualifier("userRead")
	private UserRead userRead;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	@Qualifier("userCreate")
	private Processor<Object, CreateUserBo> userCreate;
	
	@Autowired
	@Qualifier("loginRedis")
	private Processor<Void, TokenBo> loginRedis;
	
	@Autowired
	private SystemCache systemCache;
	
    /**
     * 校验
     */
    @Override
    public void check(BindBo bo) throws DzcxException {
    	String username = bo.getUsername();
    	String message = bo.getMessage();
    	if (username == null || "".equals(username.trim()) 
    			|| message == null || "".equals(message.trim())) {
    		throw new DzcxException(ExceptionCode.手机号或验证码为空);
    	}
    	
    	List<User> userList = userRead.login(username);
    	String messageDb = String.valueOf(systemCache.runFactory().get(SystemEnum.APP.key()).get(bo.getUsername() + ":" + bo.getMessageKey()));
    	if (messageDb == null || "null".equals(messageDb)) {
    		throw new DzcxException(ExceptionCode.验证码过期);
    	}
    	if (!messageDb.equals(message)) {
    		throw new DzcxException(ExceptionCode.验证码错误);
    	}
    	if (userList.size() > 1) {
    		throw new DzcxException(ExceptionCode.手机号或验证码错误);
    	}
    	
    	if (userList.isEmpty()) {
    		bo.setIsWelcome(IsEnum.是.key());
    	} else {
    		UserBean user = new UserBean();
        	User userDb = userList.get(0);
        	bo.setTargetId(userDb.getUserId());
        	BeanUtils.copyProperties(userDb, user);
        	bo.setUser(user);
    	}
    	
    	
    	
    }
    
    /**
     * 操作方法
     * @throws DzcxException 
     */
	@Override
    public BindVo process(BindBo bo) throws DzcxException {
		Integer isWelcome = bo.getIsWelcome();
		String token = UUID.randomUUID().toString();
		UserBean user = null;
		BindVo result = new BindVo();
		Long userId = null;
		if (IsEnum.否.sameKey(isWelcome)) {
			user = bo.getUser();
	    	userId = user.getUserId();
		} else {
			CreateUserBo param = new CreateUserBo();
    		param.setName("昵称-xxxx" + bo.getUsername().substring(bo.getUsername().length() - 4, bo.getUsername().length()));
    		param.setUsername(bo.getUsername());
    		param.setType(SystemCHEnum.APP.key());
    		param.setCompanyId(null);;
    		param.setRoleIdList(null);
    		param.setSex(Sex.男.key());
    		param.setAge(0);
    		param.setPhone(bo.getUsername());
    		param.setIsBatch(IsEnum.是.key());
    		
    		userCreate.process(param);
    		
    		List<User> userList = userRead.login(bo.getUsername());
    		user = new UserBean();
        	User userDb = userList.get(0);
        	bo.setTargetId(userDb.getUserId());
        	BeanUtils.copyProperties(userDb, user);
        	userId = user.getUserId();
		}
		
		result.setIsWelcome(bo.getIsWelcome());
		
		result.setUser(user);
    	result.setToken(token);
    	
    	TokenBo paramToken = new TokenBo();
    	BeanUtils.copyProperties(bo, paramToken);
    	paramToken.setToken(token);
    	paramToken.setUserId(userId);
    	loginRedis.process(paramToken);
    	
    	// app 登录绑定cid
    	String cid = bo.getCid();
    	if (cid != null && !"".equals(cid)) {
    		DetailUserVo userDb = (DetailUserVo) userRead.detail(userId);
    		Set<String> cidDb = userDb.getCid();
    		if (cidDb == null) {
    			cidDb = new HashSet<>();
    		}
    		cidDb.add(cid);
    		StringBuffer sb = new StringBuffer();
    		if (cidDb != null && cidDb.size() > 0) {
    			for (String str : cidDb) {
    				sb.append(str);
    				sb.append(",");
    			}
    			sb.deleteCharAt(sb.lastIndexOf(","));
    		}
    		String cidListStr = sb.toString();
    		User record = new User();
    		record.setUserId(userId);
    		record.setCid(cidListStr);
    		userDao.updateByPrimaryKeySelective(record);
    	}
		return result;
		
    	
    }
    
    /**
     * 操作日志
     */
	@Override
	public BindVo log(BindBo param) throws DzcxException {
		OpLog record = new OpLog();
    	record.setMoudle(MoudleEnum.基础模块.key());
    	record.setAction(LogActionEnum.app登录.key());
    	record.setTargetId(param.getTargetId());
    	record.setTargetName("用户ID:" + param.getTargetId());
    	record.setContent("参数: " + JsonUtil.toJson(param));
    	record.setReason(param.getExceptionReason());
    	
    	record.setCreatorId(param.getTargetId());
    	record.setCreator("用户ID:" + param.getTargetId());
    	record.setCreateTime(new Date());
    	log(record);
    	return null;
	}
}
